<template>
  <z-form-item
    v-if="basicForm?.isShow == '1'"
    :label-col="{ style: { width: '120px', paddingRight: '6px' } }"
    :required="formForm?.required === '1'"
    :prop="basicForm.field"
    :label="formForm?.headText && formForm?.personal == '1' ? formForm?.headText : basicForm?.titleName || '树选择'"
    class="z-form-item"
  >
    <z-tree-select
      v-if="formForm?.addOption.length > 0"
      v-model:value="model[basicForm.field]"
      :value="formForm.value"
      :disabled="formForm?.disabled === '1'"
      :placeholder="formForm?.placeHolder"
      :tree-data="addOption"
      :field-names="fieldNames"
      :tree-default-expand-all="formForm.isExpand === '1'"
      :tree-checkable="formForm.isShowCheckBox === '1'"
      :multiple="formForm?.isMulCho == '1'"
      :is-choose-last="formForm.isChooseLast === '1'"
      tree-node-label-prop="label"
      show-checked-strategy="TreeSelect.SHOW_ALL"
      @change="onSelect"
    />
  </z-form-item>
</template>
<script>
import { computed, defineComponent, toRef, ref, onMounted, watch } from 'vue'
import formInfo from '../../../api/renderForm/index.js'
import { useStore } from 'vuex'

export default defineComponent({
  name: 'TreeSelectItem',
  props: {
    formProperty: {
      type: Object,
      default: undefined
    },
    basicProperty: {
      type: Object,
      default: undefined
    },
    formModel: {
      type: Object,
      default: undefined
    },
    formList: {
      type: Array,
      default: undefined
    }
  },
  setup(props) {
    const store = useStore()

    const basicForm = toRef(props, 'basicProperty')
    const formForm = toRef(props, 'formProperty')
    const formList = toRef(props, 'formList')
    const model = computed(() => props.formModel ? props.formModel : {})

    // 数据
    let addOption = ref([])
    let list = ref([])

    // 字段名转换
    const fieldNames = computed(() => ({
      children: 'children',
      label: props.formProperty.label,
      value: props.formProperty.remoteValue,
      disabled: 'disabled'
    }))

    // 获取树选择下拉框数据
    const getDataArr = () => {
      if (formForm.value.url) {
        formInfo.getRemoteData(formForm.value.url).then(res => {
          if (res.code === 1) {
            addOption.value = res.data
          }
        })
      }
    }

    // 初始化挂载
    onMounted(() => {
      getDataArr()
    })

    // 监听当前选择组件对象数据  赋值操作
    watch(
      () => store.getters.currentVal,
      (val) => {
        let arr = store.getters.relaFieldsArr
        arr.forEach((item) => {
          if (item.assoField === basicForm.value.field) {
            model.value[basicForm.value.field] = '' || []
            formInfo.getRemoteData(item.url + store.getters.currentVal.map(i => {
              return i[item.linkField]
            })).then((res) => {
              if (res.code === 1) {
                addOption.value = res.data.map(item1 => {
                  return {
                    label: item1[item['showField']],
                    value: item1[item['replaceField']],
                    ...item1
                  }
                })
              } else {
                addOption.value = []
                model.value[basicForm.value.field] = '' || []
              }
            }).catch(() => {
              addOption.value = []
              model.value[basicForm.value.field] = '' || []
            })
          }
        })
      }
    )

    const arrayFilter = (arr, id) => {
      arr.map((val) => {
        if (id.includes(val.id)) {
          list.value.push(val)
        }
        if (val.children) {
          arrayFilter(val.children, id)
        }
      })
      return list.value
    }

    // 切换事件
    const onSelect = (value, label, extra) => {
      list.value = []
      if (!(formForm.value.isMulCho === '1' || formForm.value.isShowCheckBox === '1')) {
        store.commit('formMake/UPDATE_CURRENTVAL', [extra.allCheckedNodes[0].node.props])
      } else {
        // 去重
        let arr = Array.from(new Set(arrayFilter(addOption.value, value)))
        store.commit('formMake/UPDATE_CURRENTVAL', arr)
      }
      store.commit('formMake/UPDATE_CURRENTFIELD', basicForm.value.field)
      formList.value.forEach(item => {
        if (basicForm.value.field === item.basicProperty.field) {
          store.commit('formMake/UPDATE_ISCHANGEVAL', true)
          store.commit('formMake/UPDATE_CURRENTOBJ', item)
          store.commit('formMake/UPDATE_RELAFIELDSARR', item.formProperty.relaFields)
        }
      })
    }

    return {
      fieldNames,
      basicForm,
      formForm,
      model,
      addOption,
      onSelect
    }
  }
})
</script>
<style lang="less" scoped>
.z-form-item{
  flex: 1;
}
</style>
